import React, { Component } from "react";
import {
  BasicLayout,
  BasicLayoutSearch,
} from "../../../components/BasicLayout";
import {
  BasicPagination,
  compareNum,
  TableCustomize,
  openSuccessModal,
  openModalMessage,
  compareString,
  isInvalidObject,
} from "../../../components/TableCustomize";
import { Button, Drawer, Alert, Badge, Icon, Modal } from "antd";
import TopForm from "./TopForm";
import PickingTable from "./PickingTable";
import * as GetSuooliseService from "../../../axios/GetSuoolise";
import * as YQService from "../../../axios/api_yq";
import img from "../../../assets/img/flame.png";
import { withPermission } from '../../../components/withpermission'
const RefreshButton = withPermission(Button, 'sync')
const FBButton = withPermission(Button, 'alert')
const JJButton = withPermission(Button, 'rocket')
const CheckAllButton = withPermission(Button, 'plus')
const PrintButton = withPermission(Button, 'printer')
const DownLoadButton = withPermission(Button, 'download')
const UploadButton = withPermission(Button, 'upload')
export default class GetSuoolise extends Component {
  state = {
    dataSource: [],
    dataSourceAll: [],
    visible: false,
    searchItem: {},
    formData: {},
    drawerVisible: false,
    drawerTitle: "发布任务详细",
    selectedRows: null,
    advanced: false,
    pageNum: 1,
    pageSize: 100,
    total: 0,
    columns: [
      {
        title: "序号",
        dataIndex: "serialNumber",
        width: 60,
        render: (text, record, index) => (
          <div style={{ display: "flex" }}>
            <div>
              {(this.state.pageNum - 1) * this.state.pageSize + index + 1}
            </div>
            {record.isRush === 1 || record.isRush === "1" ? (
              <img src={img} style={{ width: "18px", height: "18px" }} />
            ) : null}
          </div>
        ),
      },
      {
        title: "批号",
        dataIndex: "batchNo",
        sorter: (a, b) => compareString(a.batchNo, b.batchNo),
        width: 100,
      },
      {
        title: "装配部门",
        dataIndex: "department",
        sorter: (a, b) => compareString(a.department, b.department),
        width: 200,
      },
      {
        title: "装配组别",
        dataIndex: "groupCode",
        sorter: (a, b) => compareString(a.groupCode, b.groupCode),
        width: 100,
      },
      {
        title: "机型",
        dataIndex: "model",
        sorter: (a, b) => compareString(a.model, b.model),
        width: 100,
      },
      {
        title: "物料编码",
        dataIndex: "partCode",
        sorter: (a, b) => compareString(a.partCode, b.partCode),
        render: (text, record, index) => (
          <div>
            {record.partChangeAttitude === 1 ? (
              <Badge status="success" text={"新增"} />
            ) : record.partChangeAttitude === 2 ? (
              <Badge status="default" text={"取消"} />
            ) : record.partChangeAttitude === 3 ? (
              <Badge status="warning" text={"属性变化"} />
            ) : record.partChangeAttitude === 4 ? (
              <Badge status="processing" text={"回仓"} />
            ) : null}
            <div>{text}</div>
          </div>
        ),
        width: 100,
      },
      {
        title: "图号",
        dataIndex: "paperCode",
        sorter: (a, b) => compareString(a.paperCode, b.paperCode),
        width: 150,
      },
      // {
      //     title: '部件',
      //     dataIndex: 'assembly',
      //     ellipsis: true,
      //     width: 60,
      // },
      {
        title: "物料名称",
        dataIndex: "partName",
        width: 150,
      },
      {
        title: "物料规格",
        dataIndex: "partSpec",
        width: 150,
      },
      {
        title: "仓库",
        dataIndex: "storeName",
        sorter: (a, b) => compareString(a.storeName, b.storeName),
        width: 100,
      },
      {
        title: "实际发料仓库",
        dataIndex: "realityStoreName",
        sorter: (a, b) => compareString(a.realityStoreName, b.realityStoreName),
        width: 150,
      },
      {
        title: "需求总数",
        dataIndex: "partNeedNum",
        sorter: (a, b) => compareNum(a.partNeedNum, b.partNeedNum),
        width: 100,
        render: (text, record) => parseInt(text),
      },
      {
        title: "领料状态",
        dataIndex: "partReceiveStatus",
        sorter: (a, b) => compareNum(a.partReceiveStatus, b.partReceiveStatus),
        width: 100,
        render: (text, record) => (
          <div>
            {record.isLack === 1 ? (
              <Badge
                status="error"
                text={<span style={{ color: "#ef929e" }}>欠料</span>}
              />
            ) : null}
            {text === "1" ? (
              <Badge
                status="default"
                text={<span style={{ color: "#d9d9d9" }}>待发布</span>}
              />
            ) : text === "2" ? (
              <Badge
                status="warning"
                text={<span style={{ color: "#ffc440" }}>待确认</span>}
              />
            ) : text === "3" ? (
              <Badge
                status="success"
                text={<span style={{ color: "#1e8e3e" }}>未完成</span>}
              />
            ) : text === "4" ? (
              <Badge
                color="#1890ff"
                text={<span style={{ color: "#1890ff" }}>已完成</span>}
              />
            ) : (
              text
            )}
          </div>
        ),
      },
      { dataIndex: "" },
    ],
    row: [],
    selectedRowKeys: [],
    selectedRows: [],
    childColumns: [
      {
        title: "序号",
        dataIndex: "serialNumber",
        width: 60,
        render: (text, record, index) => (
          <div style={{ display: "flex" }}>
            <div>
              {(this.state.pageNum - 1) * this.state.pageSize + index + 1}
            </div>
            {record.isRush === 1 || record.isRush === "1" ? (
              <img src={img} style={{ width: "18px", height: "18px" }} />
            ) : null}
          </div>
        ),
      },
      // {
      //     title: '批号',
      //     dataIndex: 'batchNo',
      //     sorter: (a, b) => compareString(a.batchNo, b.batchNo),
      //     width: 120,
      // },
      {
        title: "领料单号",
        dataIndex: "acceptCode",
        sorter: (a, b) => compareString(a.acceptCode, b.acceptCode),
        width: 140,
      },
      {
        title: "需求时间",
        dataIndex: "requestTime",
        sorter: (a, b) => compareString(a.requestTime, b.requestTime),
        width: 150,
      },
      {
        title: "领取数量",
        dataIndex: "outNumber",
        sorter: (a, b) => compareString(a.outNumber, b.outNumber),
        render: (text, record) => `${text}/${record.requestNumber}`,
        width: 100,
      },
      {
        title: "发起人/时间",
        dataIndex: "releaseTime",
        width: 180,
        render: (text, record) => (
          <p>
            <span>{record.releaseUserName}</span>
            {record.releaseUserName ? "/" : ""}
            <span>{text}</span>
          </p>
        ),
      },
      { dataIndex: "" },
    ],
    detailList: [],
    loading: false,
    issueData: {},
    acceptMap: [],
    loadingDrawer: false,
    nowDates: [],
    control: null,
    control1: false,
    GXList: [], // 工序列表
  };
  componentDidMount() {
    this.getGXList()
    const { searchItem } = this.state;
    searchItem.partReceiveStatus = "1";
    this.setState(
      {
        searchItem,
      },
      () => {
        let BomServiceID = localStorage.getItem("BomServiceID");
        GetSuooliseService.maxdid(BomServiceID ? BomServiceID : null).then(
          (value) => {
            localStorage.setItem("BomServiceID", value.data.msg);
            this.fetch();
          }
        );
      }
    );
  }
  getGXList = () => {
    YQService.queryProcessByCondition({ pageSize: 9999 }).then(res => {
      if (res.data.code != 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      let GXList = res.data.data.data || []
      this.setState({ GXList })
    })
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true });
    const { searchItem, dataSource, total } = this.state;
    searchItem.pageNum = pageNum;
    searchItem.pageSize = pageSize;
    // console.log('这是什么', searchItem);
    GetSuooliseService.acceptRequestList(searchItem)
      .then((res) => {
        // console.log(res);
        if (res.data.code !== 200) {
          openModalMessage("warning", res.data.msg);
          return;
        }
        this.setState({
          dataSource: res.data.data,
          total: res.data.total,
          pageNum,
          pageSize,
          selectedRowKeys: [],
          selectedRows: [],
          loading: false,
        });
      })
      .catch((err) => {
        openModalMessage("error", err.message);
      });
  };
  // 跨页全选
  fetchAll = async () => {
    const { searchItem, total } = this.state;
    searchItem.pageNum = 1;
    searchItem.pageSize = total;
    await GetSuooliseService.acceptRequestList(searchItem)
      .then((res) => {
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg)
          return
        }
        const dataSourceAll = res.data.data
        const selectedRowKeys = dataSourceAll.map(item => item.id);
        this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
      }).catch(err => {
        openModalMessage('error', err.message)
      })
  }
  // 高级查询
  advanced = () => {
    this.setState({ advanced: !this.state.advanced });
  };
  // 发布
  issue = () => {
    let BomServiceID = localStorage.getItem("BomServiceID");
    GetSuooliseService.maxdid(BomServiceID ? BomServiceID : null).then(
      (value) => {
        console.log(value);
        if (BomServiceID !== value.data.msg) {
          this.setState({
            control1: true,
            control: value.data.msg,
          });
          openModalMessage("warning", "数据有更新，请刷新重试");
          return;
        }
        const { selectedRows } = this.state;
        if (!selectedRows || !selectedRows.length) {
          openModalMessage("warning", "请选择要发布的数据！");
          return;
        }
        let arr = "";
        let idList = [];
        for (var item of selectedRows) {
          arr += `&idList=${item.id}`;
          idList.push(item.id)
        }
        let obj = { idList }
        // GetSuooliseService.acceptPublishList(arr)
        GetSuooliseService.acceptPublishList(obj)
          .then((res) => {
            // console.log('123231', res);
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            this.setState({
              drawerVisible: true,
              issueData: res.data.data,
            });
          })
          .catch((err) => {
            openModalMessage("error", err.message);
            return;
          });
      }
    );
  };
  // 加急
  urgent = () => {
    let BomServiceID = localStorage.getItem("BomServiceID");
    GetSuooliseService.maxdid(BomServiceID ? BomServiceID : null).then(
      (value) => {
        console.log(value);
        if (BomServiceID !== value.data.msg) {
          this.setState({
            control1: true,
            control: value.data.msg,
          });
          openModalMessage("warning", "数据有更新，请刷新重试");
          return;
        }
        const { selectedRows } = this.state;
        if (!selectedRows || !selectedRows.length) {
          openModalMessage("warning", "请选择要加急的数据！");
          return;
        }
        const that = this;
        let arr = "";
        for (var item of selectedRows) {
          arr += `&idList=${item.id}`;
        }
        for (var item of selectedRows) {
          if (item.isRush === 1 || item.isRush === "1") {
            Modal.confirm({
              title: "存在重复加急的物料",
              content: "部分物料重复加急，需要取消他们的加急状态吗？",
              icon: <Icon type="close-circle" />,
              okText: "关闭",
              cancelText: "确认",
              onOk() {
                return;
              },
              onCancel: async () => {
                await GetSuooliseService.rushSubmit(arr)
                  .then((res) => {
                    if (res.data.code !== 200) {
                      openModalMessage("warning", res.data.msg);
                      return;
                    }
                    openSuccessModal(res.data.msg);
                    this.handleCancel();
                    // that.fetch()
                  })
                  .catch((err) => {
                    openModalMessage("error", err.message);
                    return;
                  });
              },
            });
            return;
          }
        }
        this.startUrgent();
      }
    );
  };
  startUrgent = () => {
    const { selectedRows } = this.state;
    let arr = "";
    for (var item of selectedRows) {
      arr += `&idList=${item.id}`;
    }
    const that = this;
    Modal.confirm({
      title: "确认加急吗？",
      onOk: async () => {
        await GetSuooliseService.rushSubmit(arr)
          .then((res) => {
            if (res.data.code !== 200) {
              openModalMessage("warning", res.data.msg);
              return;
            }
            openSuccessModal(res.data.msg);
            this.handleCancel();
            // that.fetch()
          })
          .catch((err) => {
            openModalMessage("error", err.message);
            return;
          });
      },
      onCancel() { },
    });
  };
  // 导出
  derive = () => {
    console.log("导出");
  };
  handleSearch = (value) => {
    const { pageNum, pageSize } = this.state;
    this.setState({ searchItem: value }, () => {
      this.fetch();
    });
  };
  onHandleOk = () => {
    const { acceptMap, nowDates } = this.state;
    if (!Object.keys(acceptMap).length) {
      openModalMessage("warning", "请重新选择要发布的数据！");
      this.handleCancel();
      return;
    }
    for (var key in acceptMap) {
      if (acceptMap[key]) {
        for (var item of acceptMap[key]) {
          if (!item.requestTime) {
            openModalMessage("warning", `${item.batchNo}批号请选择需求时间！`);
            return;
          }
          if (!item.requestNumber) {
            openModalMessage("warning", `${item.batchNo}批号请输入领料数量！`);
            return;
          }
        }
      }
    }
    console.log("发布", acceptMap);
    // this.setState({ loadingDrawer: true });
    setTimeout(() => {
      // let data = {}
      // for (const key in acceptMap) {
      //     data.push({
      //         acceptPublishBodyAddDTOList: acceptMap[key],
      //         acceptCode: acceptMap[key][0].acceptCode,
      //         batchNo: acceptMap[key][0].batchNo,
      //         createTime: acceptMap[key][0].createTime,
      //         groupCode: acceptMap[key][0].groupCode,
      //         groupName: acceptMap[key][0].groupName,
      //         model: acceptMap[key][0].model,
      //         requestTime: acceptMap[key][0].requestTime,
      //         seat: acceptMap[key][0].seat,
      //     })
      // }
      // console.log(data);
      // console.log('发布数据', acceptMap);

      GetSuooliseService.acceptPublishListSubmit(acceptMap)
        .then((res) => {
          this.setState({ loadingDrawer: false });
          if (res.data.code !== 200) {
            openModalMessage("warning", res.data.msg);
            return;
          }
          localStorage.setItem("acceptPublishListSubmit", res.data.msg);
          openSuccessModal(res.data.msg);
          this.handleCancel();
        })
        .catch((err) => {
          openModalMessage("error", err.message);
          this.setState({ loadingDrawer: false });
        });
    });
  };
  // 取消
  handleCancel = () => {
    this.setState({
      visible: false,
      drawerVisible: false,
      issueData: {},
      selectedRows: [],
      selectedRowKeys: [],
    });
    this.fetch(this.state.pageNum, this.state.pageSize);
    this.state.row.length > 0 && this.onExpand(true, { id: this.state.row[0] });
  };
  // 取消
  handleCancelDrawer = () => {
    this.setState({
      drawerVisible: false,
    });
    this.state.row.length > 0 && this.onExpand(true, { id: this.state.row[0] });
  };
  // 展开方法
  onExpand = (expanded, record) => {
    // const { row } = this.state
    // let id = row.length > 0 ? row[0] : null
    // if (id == record.id) {
    //     expanded = false
    // }
    if (expanded) {
      GetSuooliseService.acceptRequestListDetail(record.id).then((res) => {
        // console.log(res)
        this.setState({
          detailList: res && res.data ? res.data.data : [],
          row: [record.id],
          expandedData: record,
        });
      });
    } else {
      this.setState({
        row: [],
      });
    }
  };
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({ searchItem: { partReceiveStatus: "1" } }, () => {
      this.fetch();
    });
  };
  // 刷新
  renewal = () => {
    const { control, control1 } = this.state;
    if (control1) {
      localStorage.setItem("BomServiceID", control);
      this.setState({
        control1: false,
      });
    }
    this.fetch();
  };
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  render() {
    const {
      advanced,
      loading,
      dataSource,
      formData,
      drawerVisible,
      drawerTitle,
      rowSelectionChild,
      columns,
      selectedRowKeys,
      pageSize,
      pageNum,
      total,
      selectedRows,
      issueData,
      loadingDrawer,
    } = this.state;
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [...this.state.selectedRowKeys];
        const rows = [...this.state.selectedRows];
        if (selected) {
          changeRows.forEach((row) => {
            if (isInvalidObject(keys.find((key) => key === row.id))) {
              keys.push(row.id);
              rows.push(row);
            }
          });
        } else {
          changeRows.forEach((row) => {
            keys.splice(keys.indexOf(row.id), 1);
            rows.splice(rows.indexOf(row), 1);
          });
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys });
      },
    };
    const expandedRowRender = () => {
      const { childColumns } = this.state;
      return (
        <TableCustomize
          rowKey={(record) => record.id}
          rowSelection={rowSelectionChild}
          dataSource={this.state.detailList}
          columns={childColumns}
          pagination={false}
          allowDrafting={true}
          scroll={{ y: 300 }}
          rowClassName={(record, index) => {
            return [
              "editable-row",
              index % 2 === 0 ? "editable-row" : "editable-row12",
            ];
          }}
        />
      );
    };
    return (
      <div>
        <BasicLayoutSearch>
          <TopForm
            onSearch={this.handleSearch}
            onClick={this.advanced}
            advanced={advanced}
            GXList={this.state.GXList}
            resetForm={this.resetForm}
            ref={(node) => (this.formSearch = node)}
          ></TopForm>
        </BasicLayoutSearch>
        <Alert
          message={
            <div>
              已选择 <span>{selectedRowKeys.length}</span> 项{" "}
              <a
                onClick={() =>
                  this.setState({ selectedRowKeys: [], selectedRows: [] })
                }
              >
                清除
              </a>{" "}
            </div>
          }
          type="info"
          showIcon
          style={{ width: "99%", margin: "auto" }}
        />
        <BasicLayout
          name={`领料申请-${localStorage.getItem("workShop")}`}
          icon="table"
          buttons={[
            <CheckAllButton key={9} onClick={this.fetchAll} icon='plus' />,
            <RefreshButton key={1} onClick={() => this.renewal()} icon='sync' />,
            <FBButton key={2} onClick={() => this.issue()} icon='alert' />,
            <JJButton key={3} onClick={() => this.urgent()} icon='rocket' />,
            // <Button
            //   type="primary"
            //   onClick={() => this.renewal()}
            //   key={3}
            //   icon="sync"
            // >
            //   刷新
            // </Button>,
            // <Button
            //   type="primary"
            //   onClick={() => this.issue()}
            //   key={1}
            //   icon="alert"
            // >
            //   发布
            // </Button>,
            // <Button
            //   type="primary"
            //   onClick={() => this.urgent()}
            //   key={2}
            //   icon="rocket"
            // >
            //   加急
            // </Button>,
            // <Button type='primary' onClick={() => this.derive()} key={4} icon="download">导出</Button>,
            // <Upload {...propss} key={5}>
            //     <Button type="primary">
            //         <Icon type="upload" /> 导入
            //     </Button>
            // </Upload>,
          ]}
        >
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            footer={(record) => {
              let partNeedNum = 0;
              record.map((item) => {
                partNeedNum += Number(item.partNeedNum);
              });
              return (
                <div style={{ display: "flex" }}>
                  <div style={{ flexBasis: "68%" }}> 数量总计</div>
                  <div style={{ flexBasis: "13%" }}>{partNeedNum}</div>
                </div>
              );
            }}
            rowClassName={(record, index) => {
              return [
                "editable-row",
                index % 2 === 0 ? "editable-row" : "editable-row12",
              ];
            }}
            rowSelection={rowSelection}
            // onRow={(record, rowKey) => ({
            //     onClick: this.onExpand.bind(this, true, record)
            // })}
            expandRowByClick={true}
            expandedRowKeys={this.state.row}
            expandedRowRender={expandedRowRender}
            onExpand={(expanded, record) => this.onExpand(expanded, record)}
            scroll={{ x: true, y: 450 }}
          />
          <BasicPagination
            pageNum={pageNum}
            pageSize={pageSize}
            total={total}
            loadData={this.fetch}
          />
        </BasicLayout>
        <Drawer
          width={1300}
          visible={drawerVisible}
          title={drawerTitle}
          onClose={this.handleCancelDrawer}
          maskClosable={false}
          destroyOnClose={true}
        >
          <PickingTable
            selectedRows={selectedRows}
            formData={formData}
            onOk={this.onHandleOk}
            onClose={this.handleCancelDrawer}
            issueData={issueData}
            saveAcceptMap={(value) =>
              this.setState(
                { acceptMap: value },
                console.log("回调拿到的数据", value)
              )
            }
            nowDates={(value) =>
              this.setState({ nowDates: value }, () => {
                console.log("创建时间", this.state.nowDates);
              })
            }
          />
          <div
            style={{
              position: "absolute",
              right: 0,
              bottom: 0,
              width: "100%",
              borderTop: "1px solid #e9e9e9",
              padding: "10px 16px",
              background: "#fff",
              textAlign: "right",
            }}
          >
            <Button
              onClick={this.handleCancelDrawer}
              style={{ marginRight: 10 }}
            >
              {"取消"}
            </Button>
            <Button
              type="primary"
              onClick={this.onHandleOk}
              loading={loadingDrawer}
            >
              {"确定发布"}
            </Button>
          </div>
        </Drawer>
      </div>
    );
  }
}
